package com.zhengbing.tj.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhengbing.tj.entity.AuditLog;
import com.zhengbing.tj.mapper.AuditLogMapper;
import com.zhengbing.tj.service.AuditLogService;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.time.LocalDateTime;

/**
 * 审计日志服务实现类
 * 实现审计日志的记录与查询功能
 *
 * @author zhengbing
 * @date 2024-08-22
 */
@Service
public class AuditLogServiceImpl extends ServiceImpl<AuditLogMapper, AuditLog> implements AuditLogService {
    
    @Autowired
    private AuditLogMapper auditLogMapper;
    
    @Override
    public boolean recordAuditLog(AuditLog log) {
        if (log == null) {
            return false;
        }
        
        // 设置操作时间
        if (log.getOperationTime() == null) {
            log.setOperationTime(LocalDateTime.now());
        }
        
        return this.save(log);
    }
    
    @Override
    public boolean batchRecordAuditLogs(List<AuditLog> logs) {
        if (logs == null || logs.isEmpty()) {
            return false;
        }
        
        // 为每条日志设置操作时间
        LocalDateTime now = LocalDateTime.now();
        for (AuditLog log : logs) {
            if (log.getOperationTime() == null) {
                log.setOperationTime(now);
            }
        }
        
        return this.saveBatch(logs);
    }
    
    @Override
    public List<AuditLog> getLogsByOperatorId(Long operatorId) {
        if (operatorId == null) {
            return null;
        }
        
        return lambdaQuery()
                .eq(AuditLog::getOperatorId, operatorId)
                .orderByDesc(AuditLog::getOperationTime)
                .list();
    }
    
    @Override
    public List<AuditLog> getLogsByEntity(String entityName, Long entityId) {
        if (entityName == null || entityId == null) {
            return null;
        }
        
        return lambdaQuery()
                .eq(AuditLog::getEntityName, entityName)
                .eq(AuditLog::getEntityId, entityId)
                .orderByDesc(AuditLog::getOperationTime)
                .list();
    }
    
    @Override
    public List<AuditLog> getLogsByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        if (startTime == null || endTime == null) {
            return null;
        }
        
        return lambdaQuery()
                .between(AuditLog::getOperationTime, startTime, endTime)
                .orderByDesc(AuditLog::getOperationTime)
                .list();
    }
    
    @Override
    public List<AuditLog> getLogsByOperationType(String operationType) {
        if (operationType == null) {
            return null;
        }
        
        return lambdaQuery()
                .eq(AuditLog::getOperationType, operationType)
                .orderByDesc(AuditLog::getOperationTime)
                .list();
    }
}